import {Component, HostBinding, OnInit} from '@angular/core';
import {FormBuilder, Validators} from '@angular/forms';
import {MatDialog, MatSnackBar} from '@angular/material';
import {CaptchaComponent} from '../captcha.component';
import {ConfigService} from '../../../service/config.service';
import {AuthService} from '../../../service/auth.service';
import {alertDialog, loadingDialog} from '../../../util/dialog.util';
import {errorSnackBar, openSnackBar} from '../../../util/snack.util';
import {slideToTop} from '../../../anim/router.anim';
import {ActivatedRoute, Router} from '@angular/router';
import {equalValidator} from '../../../util/field.validators';

@Component({
  selector: 'app-reset',
  templateUrl: './reset.component.html',
  styleUrls: ['./reset.component.css'],
  animations: [slideToTop]
})
export class ResetComponent extends CaptchaComponent implements OnInit {
  @HostBinding('@routeAnim') routeAnim;
  hide = true;
  resetPassCode: string;

  constructor(private fb: FormBuilder, private routerInfo: ActivatedRoute, private router: Router,
              public snackBar: MatSnackBar, private dialog: MatDialog,
              public configService: ConfigService, public authService: AuthService) {
    super(snackBar, configService, authService);
    this.formModel = fb.group({
      pwdGroup: fb.group({
        password: ['', [Validators.required,
          Validators.minLength(6), Validators.maxLength(32)]],
        passwordConfirm: ['', [Validators.required,
          Validators.minLength(6), Validators.maxLength(32)]],
      }, {validators: equalValidator}),
      captcha: ['', [Validators.required]]
    });
  }

  ngOnInit() {
    this.changeCaptcha();
    this.resetPassCode = this.routerInfo.snapshot.queryParams.code;
  }

  onSubmit() {
    if (this.formModel.valid && this.resetPassCode) {
      const loadingDialogRef = loadingDialog(this.dialog);
      this.authService.resetPass(
        this.resetPassCode,
        this.formModel.get('pwdGroup').get('password').value,
        this.formModel.get('captcha').value)
        .subscribe(() => {
          loadingDialogRef.close();
          alertDialog(this.dialog, '成功', '修改密码成功！');
          this.router.navigate(['/auth/login']);
        }, error1 => {
          loadingDialogRef.close();
          errorSnackBar(this.snackBar, error1);
          this.changeCaptcha();
        });
    } else {
      openSnackBar(this.snackBar, '请检查是否符合所有填写规则');
    }
  }
}
